package com.llcbenwu.social.qq.api;

import cn.hutool.json.JSONObject;
import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.llcbenwu.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.social.oauth2.AbstractOAuth2ApiBinding;
import org.springframework.social.oauth2.TokenStrategy;
import sun.dc.pr.PRError;

import java.io.IOException;

/**
 * @author lilinchun
 * @date 2021/11/1 0001 17:50
 */
@Slf4j
public class QQImpl extends AbstractOAuth2ApiBinding implements QQ {

    //获取oppenID的url
    private static  final  String URL_GET_OPENID="https://graph.qq.com/oauth2.0/me?access_token=%s";

    //获取用户详情的url
    private static   final String URL_GET_USERINFO="https://graph.qq.com/user/get_user_info?oauth_consumer_key=%s&openid=%s";

    private String appId;

    private String openId;


    public QQImpl(String accessToken,String appId){
        //调取父类的通过parameter(父类会自动将access_token自动挂在我们请求的参数上)
        super(accessToken, TokenStrategy.ACCESS_TOKEN_PARAMETER);
        this.appId=appId;

        //拼接url（就是将%s替换掉）
        String url=String.format(URL_GET_OPENID,accessToken);
        log.info("获取openId的url："+url);
        //发请求获取openId
        String result=getRestTemplate().getForObject(url,String.class);
       log.info("获取放回结果result："+result);
        //截取返回结果中的openId
        this.openId= StringUtils.substringBetween(result,"\"openid\":\"", "\"}");
    }


    /**
     * 获取用户信息
     * @return
     * @throws IOException
     */
    @Override
    public QQUserInfo getUserInfo()  {
       String url=String.format(URL_GET_USERINFO,appId,openId);
       //发请求获取用户信息（返回的是json数据）
        String forObject = getRestTemplate().getForObject(url, String.class);
        log.info("用户信息："+forObject);
        QQUserInfo qqUserInfo=null;
        //将json数据转换为实体
        qqUserInfo= JSON.parseObject(forObject,QQUserInfo.class);
//       qqUserInfo= objectMapper.readValue(forObject,QQUserInfo.class);
        assert qqUserInfo != null;
        qqUserInfo.setOpenId(openId);
        return qqUserInfo;

    }
}
